/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * main.c
 * Copyright (C) chemek anouar 2012 <anouar.chemek@esprit.tn>
 *
 * WiScramb is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * WiScramb is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include "utils.h"
#include "sniffer.h"
#include "filter.h"

int main ( int argc, char ** argv )
{

  //TODO add a linked list
  pid_t val;


  void *buffer=NULL;

  extern access_point *apvector; //tab of access_point
  extern station *stationvector; //tab of station
  extern int sta_number;
  int ap_number;

  static pthread_mutex_t Mutex;  //static pour que le compilateur n'optimise pas le code dans la section critique
  pthread_t tid1;
  pthread_t tid2;
  //pthread_t tid3;
  //static sem_t vide, plein;

  if(argc < 2)
    {
      printf("\nPréciser l'interface wifi:: %s wlan0",argv[0]);
      exit(1);
    }

  //airomon.sh execution

  if((val =fork()) == -1)
    exit(EXIT_FAILURE);


  if(!val){

      if(execl("../scripts/airmon-ng.sh","airomon.sh","start",argv[1],NULL) == -1){
          perror("error setting wlan0 in monitor mode");
      }

      exit(EXIT_SUCCESS);

  }
  printf("\n processus pere");
  //threads (freq hopper, process incomming frame , inject frame )

  pthread_mutex_init ( &Mutex, NULL );

  apvector=(struct access_point*)malloc(MAX_AP_NUMBER * sizeof(struct access_point));
  stationvector=(struct station*)malloc(MAX_STA_NUMBER * sizeof(struct station));

  if ( configure_raw_socket () == -1 ) {
      perror("error setting socket");
      return (-1);
  }


  //freq hopper

  if(pthread_create(&tid1,NULL,freq_hopper,argv[1]) == -1)
    perror("error creating freq_changer thread");

  //ieee80211_frame_process(buffer);
  if(pthread_create(&tid2,NULL,ieee80211_frame_process,buffer) == -1)
    perror("error processing incomming frame");

  pthread_join ( tid1, NULL );
  pthread_join ( tid2, NULL );


  //TODO add the others threads

  //TODO add interruption signal to stop WiScramb

  if((val =fork()) == -1)
    exit(EXIT_FAILURE);

  if(!val){

      if(execl("../scripts/airmon-ng.sh","airomon.sh","stop","mon0",NULL) == -1){
          perror("error removing monitor wireless interface");
      }
  }
  return (0);
}
